using Godot;

public partial class DayNightCycle : Node2D
{
	[Export] public float CycleDuration = 120.0f; // 昼夜循环总时长（秒）
	[Export] public float DayDuration = 80.0f;    // 白天时长（秒）
	[Export] public Color DayColor = Colors.White;      // 白天颜色
	[Export] public Color NightColor = new Color(0.2f, 0.2f, 0.4f); // 夜晚颜色
	
	private CanvasModulate _canvasModulate;
	private DirectionalLight2D _sunLight;
	private float _currentTime = 0.0f;
	private Label _timeLabel;
	private HSlider _speedSlider;
	private float _timeSpeed = 1.0f;
	
	// 时间状态枚举
	public enum TimeOfDay
	{
		Day,      // 白天
		Night     // 夜晚
	}
	
	private TimeOfDay _currentTimeOfDay = TimeOfDay.Day;
	
	public override void _Ready()
	{
		// 获取或创建CanvasModulate节点
		_canvasModulate = GetNode<CanvasModulate>("CanvasModulate");
		
		// 获取或创建DirectionalLight2D节点
		_sunLight = GetNode<DirectionalLight2D>("SunLight");
		
		// 获取时间显示标签
		_timeLabel = GetNode<Label>("UI/TimeLabel");
		
		// 获取速度控制滑块
		_speedSlider = GetNode<HSlider>("UI/ControlPanel/SpeedSlider");
		_speedSlider.ValueChanged += OnSpeedChanged;
		
		// 连接时间控制按钮
		GetNode<Button>("UI/ControlPanel/TimeButtons/DayButton").Pressed += () => SetTimeOfDay(TimeOfDay.Day);
		GetNode<Button>("UI/ControlPanel/TimeButtons/NightButton").Pressed += () => SetTimeOfDay(TimeOfDay.Night);
		
		// 初始化为白天
		_currentTime = CycleDuration * 0.25f; // 从白天开始
		UpdateDayNightCycle();
	}
	
	public override void _Process(double delta)
	{
		// 更新时间（应用时间速度）
		_currentTime += (float)delta * _timeSpeed;
		
		// 如果超过循环时长，重置时间
		if (_currentTime >= CycleDuration)
		{
			_currentTime = 0.0f;
		}
		
		UpdateDayNightCycle();
		UpdateTimeDisplay();
	}
	
	private void UpdateDayNightCycle()
	{
		// 计算当前时间在循环中的比例 (0-1)
		float timeRatio = _currentTime / CycleDuration;
		
		// 确定当前时间段
		TimeOfDay newTimeOfDay = GetCurrentTimeOfDay(timeRatio);
		
		// 如果时间段发生变化，触发事件
		if (newTimeOfDay != _currentTimeOfDay)
		{
			_currentTimeOfDay = newTimeOfDay;
			OnTimeOfDayChanged(_currentTimeOfDay);
		}
		
		// 更新光照和颜色
		UpdateLighting(timeRatio);
	}
	
	private TimeOfDay GetCurrentTimeOfDay(float timeRatio)
	{
		// 简化为只有白天和夜晚两种状态
		// 0-0.5: 夜晚, 0.5-1.0: 白天
		return timeRatio < 0.5f ? TimeOfDay.Night : TimeOfDay.Day;
	}
	
	private void UpdateLighting(float timeRatio)
	{
		Color currentColor;
		float lightIntensity;
		
		// 简化的昼夜变化：只在白天和夜晚之间平滑过渡
		if (timeRatio < 0.5f) // 夜晚
		{
			currentColor = NightColor;
			lightIntensity = 0.3f;
		}
		else // 白天
		{
			currentColor = DayColor;
			lightIntensity = 1.0f;
		}
		
		// 在过渡区域添加平滑插值（避免突变）
		float transitionZone = 0.1f; // 过渡区域宽度
		if (timeRatio > 0.5f - transitionZone && timeRatio < 0.5f + transitionZone)
		{
			// 计算过渡进度 (0-1)
			float t = (timeRatio - (0.5f - transitionZone)) / (2 * transitionZone);
			currentColor = NightColor.Lerp(DayColor, t);
			lightIntensity = Mathf.Lerp(0.3f, 1.0f, t);
		}
		
		// 应用颜色和光照
		_canvasModulate.Color = currentColor;
		_sunLight.Energy = lightIntensity;
		
		// 更新太阳角度（可选）
		float sunAngle = timeRatio * 360.0f - 90.0f; // -90度开始（东方）
		_sunLight.RotationDegrees = sunAngle;
	}
	
	private void UpdateTimeDisplay()
	{
		// 将时间比例转换为24小时制
		float timeRatio = _currentTime / CycleDuration;
		int hours = (int)(timeRatio * 24) % 24;
		int minutes = (int)((timeRatio * 24 * 60) % 60);
		
		string timeString = $"{hours:D2}:{minutes:D2}";
		string timeOfDayString = _currentTimeOfDay switch
		{
			TimeOfDay.Day => "白天",
			TimeOfDay.Night => "夜晚",
			_ => "未知"
		};
		
		_timeLabel.Text = $"时间: {timeString} ({timeOfDayString})";
	}
	
	private void OnTimeOfDayChanged(TimeOfDay newTimeOfDay)
	{
		GD.Print($"时间段变化: {newTimeOfDay}");
		
		// 在这里可以添加时间段变化时的特殊效果
		switch (newTimeOfDay)
		{
			case TimeOfDay.Day:
				GD.Print("太阳升起，新的一天开始了！");
				break;
			case TimeOfDay.Night:
				GD.Print("夜幕降临，星星开始闪烁...");
				break;
		}
	}
	
	// 公共方法：设置特定时间
	public void SetTime(float timeRatio)
	{
		_currentTime = timeRatio * CycleDuration;
		UpdateDayNightCycle();
	}
	
	// 公共方法：获取当前时间比例
	public float GetTimeRatio()
	{
		return _currentTime / CycleDuration;
	}
	
	// 公共方法：获取当前时间段
	public TimeOfDay GetCurrentTimeOfDay()
	{
		return _currentTimeOfDay;
	}
	
	private void OnSpeedChanged(double value)
	{
		_timeSpeed = (float)value;
	}
	
	// 设置特定时间段
	public void SetTimeOfDay(TimeOfDay timeOfDay)
	{
		float targetTime = timeOfDay switch
		{
			TimeOfDay.Day => 0.75f,   // 75% of cycle (白天中午)
			TimeOfDay.Night => 0.25f, // 25% of cycle (夜晚深夜)
			_ => 0.75f
		};
		
		SetTime(targetTime);
	}
}
